package com.yf.demo.disruptor;

/**
 * Created by yfxiaodou on 17-4-12.
 * 系统伪共享demo
 * 缓存系统中是以缓存行（cache line）为单位存储的。缓存行是2的整数幂个连续字节，一般为32-256个字节。
 * 最常见的缓存行大小是64个字节。当多线程修改互相独立的变量时，如果这些变量共享同一个缓存行，就会无意中影响彼此的性能，这就是伪共享
 *
 * number - cacheLine - falseSharing
 *   1  - 404.871617  -  427.233948
 *   2  - 1939.381306 -  464.396715
 *   3  - 2975.172277 -  544.744249
 *   4 -  3158.775166 -  566.374832
 */
public class FalseSharingDemo implements Runnable {
    public final static int NUM_THREADS = 4; // change
    public final static long ITERATIONS = 500L * 100000L ;
    private final int arrayIndex;

    private static VolatileLong[] longs = new VolatileLong[NUM_THREADS];

    static {
        for (int i = 0; i < longs.length; i++) {
            longs[i] = new VolatileLong();
        }
    }

    public FalseSharingDemo(final int arrayIndex) {
        this.arrayIndex = arrayIndex;
    }



    private static void runTest() throws InterruptedException {
        Thread[] threads = new Thread[NUM_THREADS];

        for (int i = 0; i < threads.length; i++) {
            threads[i] = new Thread(new FalseSharingDemo(i));
        }

        for (Thread t : threads) {
            t.start();
        }

        for (Thread t : threads) {
            t.join();
        }
    }

    public void run() {
        long i = ITERATIONS + 1;
        while (0 != --i) {
            longs[arrayIndex].value = i;
        }
    }

    public final static class VolatileLong {
        public volatile long value = 0L;
//        public long p1, p2, p3, p4, p5, p6; // comment out
    }

    public static void main(final String[] args) throws Exception {
        final long start = System.nanoTime();
        runTest();
        System.out.println("耗时 = " + (System.nanoTime() - start)/1000000.0+"秒");
    }
}